package com.pucong.gitee.database.backup.configuration.authorize;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pucong.gitee.database.backup.common.entity.sys.authorize.LicenseCheck;
import com.pucong.gitee.database.backup.utils.ApplicationContextUtil;
import com.pucong.gitee.database.backup.utils.Res;
import com.pucong.gitee.database.backup.utils.SystemConstant;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统版本校验是否可用
 * 拦截所有被 @LicenseCheck 注解 了的控制层，校验认证文件
 */
@Component
public class CertificateInterceptorAdapter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        LicenseCheck annotation = method.getMethodAnnotation(LicenseCheck.class);
        // 检测注解 非开发环境
        if (annotation != null && !ApplicationContextUtil.isDev()) {
            if (!LicenseAuth.check().getSuccess()) {
                String msg = "认证授权失败，请替换最新认证文件";
                ObjectMapper mapper = new ObjectMapper();
                Res custom = Res.custom(SystemConstant.LICENSE_FAIL, msg);
                String json = mapper.writeValueAsString(custom);
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().print(json);
                return false;
            }
        }
        return true;
    }
}
